//
//  HJCStatus.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/17.
//  Copyright (c) 2015年 heima. All rights reserved.
//
import UIKit
import SVProgressHUD
import SDWebImage

//加载首页的地址
private let FRIDENDS_TIMELINE_URL = "https://api.weibo.com/2/statuses/friends_timeline.json"

class HJCStatus: NSObject {
    
    var created_at : String?  //微博创建时间
    var id : Int = 0  //微博ID
    var text : String?  //微博信息内容
    var source : String? //微博来源
    var thumbnail_pic : String?  //缩略图片地址，没有时不返回此字段
    var reposts_count : Int = 0 //转发数
    var comments_count : Int = 0  //评论数
    var pic_urls : [[String:AnyObject]]? //微博配图
    //计算型属性，根据缩略图url，返回大图url
    var largepic_urls : [String]?{     //微博大图
        //遍历
        if pic_urls != nil{
           
            var arrayM = [String]()
            for dict  in pic_urls!{
            //缩略图的url
                let url = dict["thumbnail_pic"] as? NSString
                //替换成大图的url
               let largeUrl = url!.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                //加入可变数组中
                arrayM.append(largeUrl as String)
                
            }
            //返回
            return arrayM
        }
        return nil
    
    }
    
    var user : HJCUser?  //微博作者的用户信息
    var retweeted_status : HJCStatus? //被转发的微博
    
    //计算行属性。判断显示什么图片
    var weiboPic_urls : [[String:AnyObject]]?{
        if retweeted_status == nil{
            //如果是原创，显示原创图片
           return pic_urls
        }else{
            //如果是转发，显示转发图片
           return retweeted_status?.pic_urls
        }

    }
    //计算型属性，返回大图url数组
    var weiboLargePic_urls:[String]?{
        if retweeted_status == nil{
            return self.largepic_urls
        }else{
            //如果是转发，显示转发图片
            return retweeted_status?.largepic_urls
        }
    
    }
    
    private static let properties = ["created_at","id","text","source","thumbnail_pic","reposts_count","comments_count","pic_urls"]
    
    ///重写init。字典转模型
    init(dict : [String:AnyObject]) {
        super.init()
        //遍历字典转模型
        for key in HJCStatus.properties{
            if dict[key] != nil {
                setValue(dict[key], forKey: key)
            }
        }
        //处理user
        if dict["user"] != nil{
            self.user = HJCUser(dict: dict["user"] as! [String : AnyObject])
        }
        //处理retweeted_status
        if dict["retweeted_status"] != nil{
            retweeted_status = HJCStatus(dict: dict["retweeted_status"] as! [String : AnyObject])
        }

    }    
    
    ///从网路加载数据
    class func loadStatuses(since_id:Int,max_id:Int,finished:(statuses : [HJCStatus]?)->()){
        
        HJCStatusDAL.loadStatuses(since_id, max_id: max_id) { (array) -> () in
            
            if array == nil{
                SVProgressHUD.showErrorWithStatus("加载数据失败")
                return
            }
            
            //批量转模型
            let statuses = HJCStatus.statusesWithArray(array!)
            
            
            //缓存图片
            HJCStatus.loadweiboPicWithStatuses(statuses, finished: finished)
            
        }
        
    
    }
    
    
    ///将数组中字典装模型
    class func statusesWithArray(array : [[String:AnyObject]])->([HJCStatus]){
        //创建一个数据，接收对象
        var arrayM = [HJCStatus]()
       //遍历原数组。字典转模型
        for dict  in array{
            //创建对象
            let status = HJCStatus(dict: dict)
            arrayM.append(status)
        }
        
        return arrayM
    }
    
    ///将模型数组中得只有1张配图的时候，缓存图片
    class func loadweiboPicWithStatuses(Statuses:[HJCStatus] ,finished:(statuses : [HJCStatus]?)->()) {
        
        //创建组
        let group = dispatch_group_create()
        //遍历数组
        for status in Statuses{
            if status.weiboPic_urls?.count == 1{
                
                for pictureDict in status.weiboPic_urls!{
                    //先缓存图片
                    dispatch_group_enter(group)
                    let pictureURL = pictureDict["thumbnail_pic"] as! String
                    SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: pictureURL), options: nil, progress: { (_, _) -> Void in
                        
                        }, completed: { (_, _, _, _, _) -> Void in
                            
                            dispatch_group_leave(group)
                       })
                }
                
            }
            
    
        }
        
        //单张图片缓存完在回调
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            //回调
            finished(statuses: Statuses)
        })

    }
    
    ///从网路加载未读数据
    class func loadUnReadStatus(finished:(count:Int)->()){
        let urlStr = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        var param = ["access_token":sharedaccount!.access_token,"uid":sharedaccount!.uid]
        
        HJCNetWorkTools.requestJSON(.GET, URLString: urlStr, parameters: param) { (JSON) -> () in
            
            if JSON == nil{
               return
            }
            
            let dict = JSON as! [String:Int]
            
            let count = dict["status"]
            if count != nil{
                finished(count: count!)
            }
        }
    }

}
